package icu.smile.proxy.task;

import icu.smile.proxy.entity.ProxyMiPu;
import icu.smile.proxy.service.MiPuService;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * <p>
 * 持久化层
 * </p>
 *
 * @author starrysky
 * @since 2021/6/6
 */
@Component
@Log
public class MiPuPipeline implements Pipeline {

    @Autowired
    private MiPuService miPuService;
    private volatile static int curIndex = 0;
    private static final Logger LOGGER = Logger.getLogger(MiPuPipeline.class.getName());


    @Override
    public void process(ResultItems resultItems, Task task) {

        final ProxyMiPu proxyMiPu = new ProxyMiPu();
        final List<String> ip = resultItems.get("ip");
        final List<Integer> port = resultItems.get("port");
        final List<String> type = resultItems.get("type");
        final List<String> anonymous = resultItems.get("anonymous");
        final List<String> location = resultItems.get("location");
        final List<String> operator = resultItems.get("operator");
        final List<String> responseTime = resultItems.get("responseTime");
        final List<String> transmissionTime = resultItems.get("transmissionTime");
        final List<String> verificationTime = resultItems.get("verificationTime");
        final List<ProxyMiPu> entityList = new ArrayList<>();

        if (ip.size() == 0 || port.size() == 0) {
            return;
        }

        for (int i = curIndex; i <= ip.size() - 1; i++) {
            proxyMiPu.setIp(ip.get(i))
                    .setPort(port.get(i))
                    .setType(type.size() == 0 ? "页面无类型描述" : type.get(i))
                    .setAnonymous(anonymous.size() == 0 ? "页面无描述" : anonymous.get(i))
                    .setLocation(location.size() == 0 ? "页面无地址描述" : location.get(i))
                    .setOperator(operator.size() == 0 ? "页面无运营商描述" : operator.get(i))
                    .setResponseTime(responseTime.size() == 0 ? "页面无响应时间描述" : responseTime.get(i))
                    .setTransmissionTime(transmissionTime.size() == 0 ? "页面无传输时间描述" : transmissionTime.get(i))
                    .setVerificationTime(verificationTime.size() == 0 ? "页面无验证时间描述" : verificationTime.get(i));
                entityList.add(proxyMiPu);
                LOGGER.info(proxyMiPu.toString());
        }
        miPuService.saveAll(entityList);
        curIndex = 0;

    }
}
